// 公会模块
package player

import (
	"GameServer/Common/utils"
	"strings"

	"GameServer/Common/data"
	"GameServer/Game/errors"
	"GameServer/Game/lib"
	"GameServer/Game/m"
	"GameServer/Game/rank"
	"GameServer/Game/sp"
	"GameServer/Game/union"

	log "github.com/sirupsen/logrus"
)

// 创建公会 1001
func (p *Player) CreateUnionRequest(req *sp.CreateUnionRequest) (res *sp.CreateUnionResponse, err error) {
	us := p.User
	req.Name = strings.TrimSpace(req.Name)
	req.ShortName = strings.TrimSpace(req.ShortName)
	if len(req.Name) <= 4 {
		res = &sp.CreateUnionResponse{
			Errcode: data.Errcode.ServerErr,
		}
		log.WithFields(log.Fields{
			"uid":    p.User.Uid.Hex(),
			"method": "CreateUnionRequest",
			"data":   req.Name,
		}).Debug("公会名称小于4个字符")
		return
	}

	if len(req.ShortName) != 4 {
		res = &sp.CreateUnionResponse{
			Errcode: data.Errcode.ServerErr,
		}
		log.WithFields(log.Fields{
			"uid":    p.User.Uid.Hex(),
			"method": "CreateUnionRequest",
			"data":   req.ShortName,
		}).Debug("公会短名称不等于4个字符")
		return
	}

	uProp, union, members, err := lib.UnionCreate(us, req)
	if err != nil {
		res = &sp.CreateUnionResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}

	// 公会签到积分信息
	endTime, integral, surplus, err := lib.HandleUnionSignIn(us)
	if err != nil {
		res = &sp.CreateUnionResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 初始化公会体力请求
	us.GetUnionEnergy().Clear()
	// 初始化公会红包请求
	m.GetUnionRedPacket(us.Uid.Hex()).Clear()

	res = &sp.CreateUnionResponse{
		Info:     lib.FormatUnionInfoSp(union),
		Members:  lib.FormatUnionMemberSps(members),
		EndTime:  endTime,
		Integral: integral,
		Surplus:  surplus,
	}
	p.TimelyUpdateProp(req.GetType(), uProp)
	utils.AsyncFunc(func() {
		p.UpdateProp(req.GetType(), uProp)
	})
	return
}

// 获取公会列表 1002
func (p *Player) UnionListRequest(req *sp.UnionListRequest) (res *sp.UnionListResponse) {
	list, num := union.UnionModule.UnionList(int(req.Page), int(req.PageNum))
	res = &sp.UnionListResponse{
		List: lib.FormatUnionInfoSps(list),
		Num:  int64(num),
	}
	return
}

// 1004 加入公会
func (p *Player) UnionAddRequest(req *sp.UnionAddRequest) (res *sp.UnionAddResponse, err error) {
	us := p.User
	if p.User.GetUnionBan().IsBan(req.Id) {
		res = &sp.UnionAddResponse{
			Errcode: data.Errcode.UnionIsBan,
		}
		return
	}

	runion, members, err := union.UnionModule.UnionAddMerber(us, req.Id, BroadData)
	if err != nil {
		res = &sp.UnionAddResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 公会签到积分信息
	endTime, integral, surplus, err := lib.HandleUnionSignIn(us)
	if err != nil {
		res = &sp.UnionAddResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 初始化公会体力请求
	us.GetUnionEnergy().Clear()
	// 初始化公会红包请求
	m.GetUnionRedPacket(us.Uid.Hex()).Clear()

	res = &sp.UnionAddResponse{
		Info:     lib.FormatUnionInfoSp(runion),
		Members:  lib.FormatUnionMemberSps(members),
		EndTime:  endTime,
		Integral: integral,
		Surplus:  surplus,
	}

	name := p.User.Name
	unionId := runion.Id.Hex()
	utils.AsyncFunc(func() {
		union.UnionModule.UnionSysNotice(unionId, data.LangID.UnionJoin, []string{name}, BroadData)
	})

	// 成就，记录添加工会。
	lib.AddAchievProgress(p.User, data.AchievementType.Join_guild, 1)
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	return
}

// 1005 退出公会
func (p *Player) UnionQuitRequest(req *sp.UnionQuitRequest) (res *sp.UnionQuitResponse, err error) {
	if p.User.UnionId == "" {
		res = &sp.UnionQuitResponse{
			Errcode: data.Errcode.NoUnion,
		}
		return
	}
	err = union.UnionModule.UnionQuit(p.User.UnionId, p.User, BroadData)
	if err != nil {
		res = &sp.UnionQuitResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	res = &sp.UnionQuitResponse{}
	return
}

// 1006 公会 踢出玩家
func (p *Player) UnionBanRequest(req *sp.UnionBanRequest) (res *sp.UnionBanResponse, err error) {
	if req.Uid == p.User.Uid.Hex() {
		return
	}
	tu, ok := GetUser(req.Uid)
	if !ok {
		res = &sp.UnionBanResponse{
			Errcode: data.Errcode.NoUnionUser,
		}
		return
	}
	err = union.UnionModule.UnionBan(p.User.UnionId, p.User.Uid.Hex(), tu, BroadData)
	if err != nil {
		res = &sp.UnionBanResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	res = &sp.UnionBanResponse{}
	return
}

func (p *Player) UnionSearchRequest(req *sp.UnionSearchRequest) (res *sp.UnionSearchResponse, err error) {
	unions, err := union.UnionModule.UnionSearch(req.Name)
	if err != nil {
		res = &sp.UnionSearchResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	res = &sp.UnionSearchResponse{
		Info: lib.FormatUnionInfoSps(unions),
	}
	return
}

// 1003 获取公会信息
func (p *Player) UnionInfoRequest(req *sp.UnionInfoRequest) (res *sp.UnionInfoResponse, err error) {
	union, members, err := union.UnionModule.UnionInfo(req.Id)
	if err != nil {
		res = &sp.UnionInfoResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	res = &sp.UnionInfoResponse{
		Info:    lib.FormatUnionInfoSp(union),
		Members: lib.FormatUnionMemberSps(members),
	}
	return
}

func (p *Player) UnionInfoEditRequest(req *sp.UnionInfoEditRequest) (res *sp.UnionInfoEditResponse, err error) {
	req.Name = strings.TrimSpace(req.Name)
	req.ShortName = strings.TrimSpace(req.ShortName)
	if req.Name != "" && len(req.Name) <= 4 {
		res = &sp.UnionInfoEditResponse{
			Errcode: data.Errcode.ServerErr,
		}
		log.WithFields(log.Fields{
			"uid":    p.User.Uid.Hex(),
			"method": "UnionInfoEditRequest",
			"data":   req.Name,
		}).Debug("公会名称小于4个字符")
		return
	}

	if req.ShortName != "" && len(req.ShortName) != 4 {
		res = &sp.UnionInfoEditResponse{
			Errcode: data.Errcode.ServerErr,
		}
		log.WithFields(log.Fields{
			"uid":    p.User.Uid.Hex(),
			"method": "UnionInfoEditRequest",
			"data":   req.ShortName,
		}).Debug("公会短名称不等于4个字符")
		return
	}
	err = union.UnionModule.UpdateUnionInfo(p.User.UnionId, p.User.Uid.Hex(), req, BroadData)
	if err != nil {
		res = &sp.UnionInfoEditResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	res = &sp.UnionInfoEditResponse{}
	return
}

// 1015 公会消息列表 聊天信息
func (p *Player) UnionChatMsgListRequest(req *sp.UnionChatMsgListRequest) (res *sp.UnionChatMsgListResponse, err error) {
	rList, num, err := union.UnionModule.UnionChatList(p.User.UnionId, req)
	if err != nil {
		res = &sp.UnionChatMsgListResponse{
			Errcode: data.Errcode.ServerErr,
		}
		log.WithFields(log.Fields{
			"uid":    p.User.Uid.Hex(),
			"method": "UnionChatMsgListRequest",
		}).Error(err)
		return
	}
	res = &sp.UnionChatMsgListResponse{
		Msglist: lib.FormatUnionChatMstSps(rList),
		Num:     int64(num),
	}
	return
}

// 1016 公会会长禅让
func (p *Player) UnionPresidentAbdicatedRequest(req *sp.UnionPresidentAbdicatedRequest) (res *sp.UnionPresidentAbdicatedResponse, err error) {

	err = union.UnionModule.PresidentAbdicated(p.User.UnionId, req.LeaderUid, req.HeirUid, BroadData)
	if err != nil {
		res = &sp.UnionPresidentAbdicatedResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}

	res = &sp.UnionPresidentAbdicatedResponse{}
	return
}

func (p *Player) StarChange() {
	if p == nil || p.User == nil {
		return
	}
	rank.AddUserRank(p.User)
	p.User.StarChangeTime = utils.TNow().Unix()
	if p.User.UnionId == "" {
		return
	}
	star := p.User.StarVal()
	union.UnionModule.UpdateUserStar(p.User.UnionId, p.User.Uid.Hex(), star, BroadData)
}

func (p *Player) UnionScoreChange() {
	if p.User.UnionId == "" {
		return
	}
	union.UnionModule.UpdateUserScore(p.User.UnionId, p.User.Uid.Hex(), p.User.UnionScore, BroadData)
}

func (p *Player) PlayerAvatarFrameChange() {
	if p == nil || p.User == nil {
		return
	}
	if p.User.UnionId == "" {
		return
	}
	union.UnionModule.UpdateUserAvatarFrame(p.User.UnionId, p.User.Uid.Hex(), p.User.AvatarFrame, BroadData)
}

// 玩家的名字和头像被修改，通知工会
func (p *Player) PlayerNameAndHeadChange() {
	if p == nil || p.User == nil {
		return
	}
	if p.User.UnionId == "" {
		return
	}
	union.UnionModule.UpdateUserNameAndHead(p.User, BroadData)
}

// 推荐公会
func (p *Player) RecomUnion() {
	utils.AsyncFunc(func() {
		unionInfo, rankId := union.UnionModule.RecomUnion()
		p.Send(&sp.RecomUnionRequest{
			Info:   lib.FormatUnionInfoSp(unionInfo),
			RankId: rankId,
		})
	})
}

// 1019 公会所有信息
func (p *Player) UnionAllInfoRequest(req *sp.UnionAllInfoRequest) (res *sp.UnionAllInfoResponse) {
	us := p.User
	if us.UnionId == "" {
		res = &sp.UnionAllInfoResponse{
			Errcode: data.Errcode.NoUnion,
		}
		return
	}
	// 获取公会信息，和公会成员信息
	unionInfo, members, err := union.UnionModule.UnionInfo(us.UnionId)
	if err != nil {
		res = &sp.UnionAllInfoResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	if us.UnionJionTime == 0 {
		// 获取加入公会时间
		uid := us.Uid.Hex()
		for key, val := range members {
			if uid == key {
				us.UnionJionTime = val.JoinTime
				us.Update(us)
				break
			}
		}
	}

	// 获取公会聊天信息
	msglist, msgNum, err := union.UnionModule.UnionChatListAll(us.UnionId)
	if err != nil {
		res = &sp.UnionAllInfoResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 赠送体力列表
	enSendlist := us.GetUnionEnergy().SendList()
	// 公会签到积分信息
	endTime, integral, surplus, err := lib.HandleUnionSignIn(us)
	if err != nil {
		res = &sp.UnionAllInfoResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 领取红包的列表
	redPacket := m.GetUnionRedPacket(us.Uid.Hex())

	res = &sp.UnionAllInfoResponse{
		UnionInfo:  lib.FormatUnionInfoSp(unionInfo),
		Members:    lib.FormatUnionMemberSps(members),
		Msglist:    lib.FormatUnionChatMstSps(msglist),
		EnSendlist: lib.FormatUnionEnergySendSps(enSendlist),
		MsgNum:     int64(msgNum),
		EndTime:    endTime,
		Integral:   integral,
		Surplus:    surplus,
		RedLst:     lib.FormatRecvRedPacketInfoSps(redPacket.RecvRedPacket),
	}
	return
}
